package cn.ekuma.pos.pda.inventory.editor;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import com.openbravo.bean.AttributeSet;
import com.openbravo.bean.Product;
import com.openbravo.bean.ProductCategory;
import com.openbravo.bean.TaxCategory;
import com.openbravo.data.basic.BasicException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import cn.ekuma.android.AdapterFactory;
import cn.ekuma.data.ui.android.AbstractBaseBeanListAdapter;
import cn.ekuma.data.ui.android.AbstractFinderActivate;
import cn.ekuma.data.ui.android.editor.AbstractDAOJEditor;
import cn.ekuma.data.ui.android.editor.DirtyManager;
import cn.ekuma.epos.android.finder.ProductCategoryFinderActivate;
import cn.ekuma.epos.android.util.AbstractCacheAbleQueryOneAsyncTask;
import cn.ekuma.epos.android.util.AbstractQueryAsyncTask;
import cn.ekuma.epos.datalogic.DataLogicPDA;
import cn.ekuma.pos.android.erp.R;
import cn.trinea.android.common.service.impl.SimpleCache;

public class ProductEditor extends AbstractDAOJEditor<Product> implements TabHost.TabContentFactory{

	private TabHost tabs;
    private EditText edt_product_name;
    private EditText edt_product_code,edt_product_jiancheng,edt_product_costprice,edt_product_sellpirce,edt_product_customerprice,edt_product_costpifa;
    private Spinner spin_product_taxCategory,spin_product_attributeSet;
    private EditText edt_product_pingpai,edt_product_chandi,edt_product_zhibao,edt_product_similarCode;
    HashMap<String, View> tabViewsMap;

    private AbstractBaseBeanListAdapter<TaxCategory> taxCategoryAdapter;

    public static final int SELECT_PRODUCTCATEGORY=REQUEST_CODE+1;
    private ProductCategory productCategory;

    private Button btn_product_category;
    SimpleCache<String,ProductCategory> simpleCache;

    private AbstractBaseBeanListAdapter<AttributeSet> attributeSetAdapter;
    private EditText edt_product_weight;
    private CheckBox chb_product_iscatory;
    private CheckBox chb_product_isCom,chb_product_isBomStore,chb_product_isScale;
    private EditText edt_product_ref;

    public ProductEditor(DirtyManager dirty, Context context,android.util.AttributeSet attr) {
		super(dirty, context,attr);
	}

	public void refresh() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init(final Context context) {
		View mainView = LayoutInflater.from(context).inflate( 
                R.layout.product, this); 
        tabs=(TabHost)findViewById(R.id.tabhost);

        tabViewsMap=new HashMap<String,View>();
        View base=LayoutInflater.from(context).inflate(R.layout.product_base, null);
        tabViewsMap.put("base",base);
        View ext=LayoutInflater.from(context).inflate(R.layout.product_ext, null);
        tabViewsMap.put("ext",ext);
        View stock=LayoutInflater.from(context).inflate(R.layout.product_stock, null);
        tabViewsMap.put("stock",stock);

        tabs.setup();
        TextView ver=new TextView(context);
        ver.setText("基本");
        setupTab(ver, "base");
        ver= new TextView(context);
        ver.setText("扩展");
	    setupTab(ver, "ext");
        ver=new TextView(context);
        ver.setText("库存");
	    setupTab(ver, "stock");
        tabs.setCurrentTab(0);

        edt_product_name = (EditText) base.findViewById(R.id.productDialyTxt);
        edt_product_code= (EditText) base.findViewById(R.id.edt_product_code);
        edt_product_jiancheng= (EditText) base.findViewById(R.id.edt_product_jiancheng);
        edt_product_costprice= (EditText) base.findViewById(R.id.edt_product_costprice);
        edt_product_sellpirce= (EditText) base.findViewById(R.id.edt_product_sellpirce);
        edt_product_customerprice= (EditText) base.findViewById(R.id.edt_product_customerprice);
        edt_product_costpifa= (EditText) base.findViewById(R.id.edt_product_costpifa);
        edt_product_ref=(EditText) base.findViewById(R.id.edt_product_ref);

        edt_product_name.addTextChangedListener(dirty);
        edt_product_code.addTextChangedListener(dirty);
        edt_product_jiancheng.addTextChangedListener(dirty);
        edt_product_costprice.addTextChangedListener(dirty);
        edt_product_sellpirce.addTextChangedListener(dirty);
        edt_product_customerprice.addTextChangedListener(dirty);
        edt_product_costpifa.addTextChangedListener(dirty);
        edt_product_ref.addTextChangedListener(dirty);

        btn_product_category= (Button) base.findViewById(R.id.btn_product_category);
        btn_product_category.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                Activity activity = (Activity) context;
                intent.setClass(activity,ProductCategoryFinderActivate.class);
                activity.startActivityForResult(intent, SELECT_PRODUCTCATEGORY);
            }
        });
        spin_product_taxCategory= (Spinner) base.findViewById(R.id.spin_product_taxCategory);

        taxCategoryAdapter=new AbstractBaseBeanListAdapter<TaxCategory>(context){
            @Override
            public String cracteBaseBeanToShowText(TaxCategory obj) {
                return obj.getName();
            }
        };
        spin_product_taxCategory.setAdapter(taxCategoryAdapter);
        spin_product_taxCategory.setOnItemSelectedListener(dirty);

        simpleCache=new  SimpleCache<String,ProductCategory>();

        spin_product_attributeSet=(Spinner)base.findViewById(R.id.spin_product_attributeSet);
        attributeSetAdapter=new AbstractBaseBeanListAdapter<AttributeSet>(context){
            @Override
            public String cracteBaseBeanToShowText(AttributeSet obj) {
                return obj.getName();
            }
        };
        spin_product_attributeSet.setAdapter(AdapterFactory.nullAble(attributeSetAdapter));
        spin_product_attributeSet.setOnItemSelectedListener(dirty);

        edt_product_pingpai = (EditText) ext.findViewById(R.id.txt_product_pingpai);
        edt_product_chandi= (EditText) ext.findViewById(R.id.edt_product_chandi);
        edt_product_zhibao= (EditText) ext.findViewById(R.id.edt_product_zhibao);
        edt_product_similarCode= (EditText) ext.findViewById(R.id.edt_product_similarCode);

        edt_product_pingpai.addTextChangedListener(dirty);
        edt_product_chandi.addTextChangedListener(dirty);
        edt_product_zhibao.addTextChangedListener(dirty);
        edt_product_similarCode.addTextChangedListener(dirty);


        edt_product_weight=(EditText) stock.findViewById(R.id.edt_product_weight);
        chb_product_iscatory=(CheckBox)stock.findViewById(R.id.chb_product_iscatory);
        chb_product_isCom=(CheckBox)stock.findViewById(R.id.chb_product_isCom);
        chb_product_isBomStore=(CheckBox)stock.findViewById(R.id.chb_product_isBomStore);
        chb_product_isScale=(CheckBox)stock.findViewById(R.id.chb_product_isScale);

        edt_product_weight.addTextChangedListener(dirty);
        chb_product_iscatory.setOnClickListener(dirty);
        chb_product_isCom.setOnClickListener(dirty);
        chb_product_isBomStore.setOnClickListener(dirty);
        chb_product_isScale.setOnClickListener(dirty);
	}
	

	private void setupTab(final View view, final String tag) {
        
		TabSpec setContent = tabs.newTabSpec(tag).setIndicator(view).setContent(this);

	     tabs.addTab(setContent);

	}

    static SimpleDateFormat sdf=new SimpleDateFormat("SSSSddmm");
	@Override
	public Product createNew(Properties prop) {
		Product obj=new Product();
        String code=sdf.format(new Date());
        obj.setReference(code);
        obj.setCurDate(new Date());
		return obj;
	}

	@Override
	public void rebuild(Product obj) throws BasicException {
        obj.setName(edt_product_name.getText().toString());
        obj.setReference(edt_product_ref.getText().toString());
        obj.setCode(edt_product_code.getText().toString());
        obj.setMnemonic(edt_product_jiancheng.getText().toString());
        try {
            obj.setPriceBuy(df.parse(edt_product_costprice.getText().toString()).doubleValue());

        obj.setPriceSell(df.parse(edt_product_sellpirce.getText().toString()).doubleValue());
        obj.setM_dCustomerPrice(df.parse(edt_product_customerprice.getText().toString()).doubleValue());
        obj.setM_dWholesalePrice(df.parse(edt_product_costpifa.getText().toString()).doubleValue());

        obj.setM_sManufacturer(edt_product_pingpai.getText().toString());
        obj.setSpecification(edt_product_chandi.getText().toString());
        obj.setM_iDurability(df.parse(edt_product_zhibao.getText().toString()).intValue());
        obj.setM_sSimilarCode(edt_product_similarCode.getText().toString());

        obj.setWeight(df.parse(edt_product_weight.getText().toString()).doubleValue());
        obj.setCom(chb_product_isCom.isChecked());
        obj.setBomStore(chb_product_isBomStore.isChecked());
        obj.setScale(chb_product_isScale.isChecked());
        obj.setCategoryID(productCategory.getID());
        obj.setTaxCategoryID(((TaxCategory)spin_product_taxCategory.getSelectedItem()).getID());
        } catch (ParseException e) {
            throw new BasicException(e);
        }
        Object attr=spin_product_attributeSet.getSelectedItem();
        if(attr==null)
            obj.setAttributeSetID(null);
        else
            obj.setAttributeSetID(((AttributeSet)attr).getId());
	}


    public void activate() throws BasicException{
        AbstractQueryAsyncTask initLoadTaxCategoryTask=new AbstractQueryAsyncTask<TaxCategory>(){
            @Override
            protected List<TaxCategory> query() throws Exception {
                return (List<TaxCategory>)DataLogicPDA.getDLERP().listWithClassName(TaxCategory.class.getName());
            }

            @Override
            protected void queryResert(List<TaxCategory> result) {
                taxCategoryAdapter.clear();
                taxCategoryAdapter.addAll(result);
            }

            @Override
            protected void queryError(int type) {
                Toast.makeText(ProductEditor.this.getContext(), "执行出错了", Toast.LENGTH_LONG).show();
            }
        };
       initLoadTaxCategoryTask.execute(1);

        AbstractQueryAsyncTask initLoadAttributeSetTask=new AbstractQueryAsyncTask<AttributeSet>(){
            @Override
            protected List<AttributeSet> query() throws Exception {
                return (List<AttributeSet>)DataLogicPDA.getDLERP().listWithClassName(AttributeSet.class.getName());
            }

            @Override
            protected void queryResert(List<AttributeSet> result) {
                attributeSetAdapter.clear();
                attributeSetAdapter.addAll(result);
            }

            @Override
            protected void queryError(int type) {
                Toast.makeText(ProductEditor.this.getContext(), "执行出错了", Toast.LENGTH_LONG).show();
            }
        };
        initLoadAttributeSetTask.execute(1);
    }

    DecimalFormat df = new DecimalFormat();
	@Override
	public void updateUI(boolean editAble, int state) {
        edt_product_name.setText(this.obj.getName());
        edt_product_code.setText(obj.getCode());
        edt_product_ref.setText(obj.getReference());
        edt_product_jiancheng.setText(obj.getMnemonic());
        edt_product_costprice.setText(df.format(obj.getPriceBuy()));
        edt_product_sellpirce.setText(df.format(obj.getPriceSell()));
        edt_product_customerprice.setText(df.format(obj.getM_dCustomerPrice()));
        edt_product_costpifa.setText(df.format(obj.getM_dWholesalePrice()));

        edt_product_pingpai.setText(obj.getM_sManufacturer());
        edt_product_chandi.setText(obj.getSpecification());
        edt_product_zhibao.setText(df.format(obj.getM_iDurability()));
        edt_product_similarCode.setText(obj.getM_sSimilarCode());

        edt_product_weight.setText(df.format(obj.getWeight()));
        //chb_product_iscatory.setSelected(obj.);
        chb_product_isCom.setSelected(obj.isCom());
        chb_product_isBomStore.setSelected(obj.isBomStore());
        chb_product_isScale.setSelected(obj.isScale());

        spin_product_taxCategory.setSelection(taxCategoryAdapter.getPositionByObjectId(obj.getTaxCategoryID()),true);
        spin_product_attributeSet.setSelection(attributeSetAdapter.getPositionByObjectId(obj.getAttributeSetID())+1,true);
        if(state==this.STATE_Edit){
            if(productCategory==null||productCategory.getKey()!=obj.getCategoryID()){
               new AbstractCacheAbleQueryOneAsyncTask<ProductCategory,String>(simpleCache){

                   @Override
                   protected ProductCategory query(String param) throws Exception {
                       return (ProductCategory) DataLogicPDA.getDLERP().findByStringId(ProductCategory.class,param);
                   }

                   @Override
                   protected void queryResert(ProductCategory result) {
                       productCategory=result;
                       btn_product_category.setText(productCategory.getName());
                   }

                   @Override
                   protected void queryNoFind() {
                       productCategory=null;
                       btn_product_category.setText(null);
                   }

                   @Override
                   protected void queryError(int type) {

                   }
               }.execute(obj.getCategoryID());
            }
        }



        edt_product_name.setEnabled(editAble);
        edt_product_code.setEnabled(editAble);
        edt_product_ref.setEnabled(editAble);
        edt_product_jiancheng.setEnabled(editAble);
        edt_product_costprice.setEnabled(editAble);
        edt_product_sellpirce.setEnabled(editAble);
        edt_product_customerprice.setEnabled(editAble);
        edt_product_costpifa.setEnabled(editAble);

        edt_product_pingpai.setEnabled(editAble);
        edt_product_chandi.setEnabled(editAble);
        edt_product_zhibao.setEnabled(editAble);
        edt_product_similarCode.setEnabled(editAble);

        edt_product_weight.setEnabled(editAble);
        chb_product_iscatory.setEnabled(editAble);
        chb_product_isCom.setEnabled(editAble);
        chb_product_isBomStore.setEnabled(editAble);
        chb_product_isScale.setEnabled(editAble);

        btn_product_category.setEnabled(editAble);
        spin_product_attributeSet.setEnabled(editAble);
        spin_product_taxCategory.setEnabled(editAble);

	}

	@Override
	public Class getEditClass() {	
		return Product.class;
	}

	public View createTabContent(String arg0) {
		return tabViewsMap.get(arg0);
	}

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==Activity.RESULT_OK){
            switch(requestCode){
                case SELECT_PRODUCTCATEGORY:
                    productCategory=(ProductCategory) data.getSerializableExtra(AbstractFinderActivate.SELECTED_BEAN);
                    btn_product_category.setText(productCategory.getName());
                    break;
            }
        }else{
            switch(requestCode){
                case SELECT_PRODUCTCATEGORY:
                    productCategory=null;
                    btn_product_category.setText(null);
                    break;
            }
        }
       dirty.setDirty(true);
    }
}
